package com.group15.phms;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import android.support.v4.app.NavUtils;

public class Search extends Activity implements OnEditorActionListener
{
	String currentUser;
	SharedPreferences logins;
	
	DatabaseHelper db;
	SimpleAdapter adapter;
	ArrayList<Map<String, String>> data;
	
	ListView ItemList;
	List<Doctor> doctors;
	List<Contact> contacts;
	List<Medication> meds;
	
	String search;
	int buttonTracker = 0;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_search);
		
		// Show the Up button in the action bar.
		setupActionBar();
		
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_search);
		
		// Show the Up button in the action bar.
		getActionBar().setDisplayHomeAsUpEnabled(true);
		
		logins = getSharedPreferences("logins",MODE_PRIVATE);
		currentUser = logins.getString("currentUser","INVALID");
		
		ButtonDoctorsClicked(findViewById(R.id.buttonDoctors));
	}

	public void ButtonDoctorsClicked(View v)
	{
		buttonTracker = 1;
		final EditText s = (EditText) findViewById(R.id.editTextSearch);
		s.setText("");
		s.setHint("Search doctors...");
		s.setOnEditorActionListener(new OnEditorActionListener() 
		{
		    @Override
		    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) 
		    {
		        if(actionId == EditorInfo.IME_ACTION_DONE)
		        {
		        	 ButtonSearchClicked(findViewById(R.id.buttonSearch));
		        }
		    return false;
		    }
		});
	}
	
	public void ButtonContactsClicked(View v)
	{
		buttonTracker = 2;
		final EditText s = (EditText) findViewById(R.id.editTextSearch);
		s.setText("");
		s.setHint("Search contacts...");
		s.setOnEditorActionListener(new OnEditorActionListener() 
		{
		    @Override
		    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) 
		    {
		        if(actionId == EditorInfo.IME_ACTION_DONE)
		        {
		        	 ButtonSearchClicked(findViewById(R.id.buttonSearch));
		        }
		    return false;
		    }
		});
	}
	
	public void ButtonMedsClicked(View v)
	{
		buttonTracker = 3;
		final EditText s = (EditText) findViewById(R.id.editTextSearch);
		s.setText("");
		s.setHint("Search medication...");
		s.setOnEditorActionListener(new OnEditorActionListener() 
		{
		    @Override
		    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) 
		    {
		        if(actionId == EditorInfo.IME_ACTION_DONE)
		        {
		        	 ButtonSearchClicked(findViewById(R.id.buttonSearch));
		        }
		    return false;
		    }
		});
	}
	
	public void ButtonSearchClicked(View v)
	{
		if(buttonTracker == 1)
		{
			db= new DatabaseHelper(getApplicationContext());
			final EditText s = (EditText) findViewById(R.id.editTextSearch);
			search = s.getText().toString();
			
			doctors = db.searchDoctors(currentUser, search);
			db.closeDB();
			
			data = new ArrayList<Map<String, String>>();
			for (Doctor d : doctors) 
			{
			    Map<String, String> datum = new HashMap<String, String>(2);
			    datum.put("name", d.getName());
			    datum.put("email", d.getEmail());
			    data.add(datum);
			    
				adapter = new SimpleAdapter(this, data, R.layout.doctor_row, new String[] {"name", "email"},
	                    new int[] {R.id.toptext, R.id.bottomtext});
				ListView itemList = (ListView) findViewById(R.id.listViewSearch);
				itemList.setAdapter(adapter);
				itemList.setEmptyView(findViewById(R.id.empty));
			}
		}
		else if(buttonTracker == 2)
		{
			db= new DatabaseHelper(getApplicationContext());
			final EditText s = (EditText) findViewById(R.id.editTextSearch);
			search = s.getText().toString();
			
			contacts = db.searchContacts(currentUser, search);
			db.closeDB();
			data = new ArrayList<Map<String, String>>();
			for (Contact c : contacts) 
			{
			    Map<String, String> datum = new HashMap<String, String>(3);
			    datum.put("name", c.getName());
			    datum.put("email", c.getEmail());
			    datum.put("phone", c.getPhone());
			    data.add(datum);
			}
			
			adapter = new SimpleAdapter(this, data, R.layout.contact_row, new String[] {"name", "email", "phone"}, 
					new int[] {R.id.toptext, R.id.centertext, R.id.bottomtext});
			
			ListView itemList = (ListView)findViewById(R.id.listViewSearch);
			itemList.setAdapter(adapter);
			itemList.setEmptyView(findViewById(R.id.empty));
		}
		else if(buttonTracker == 3)
		{
			db= new DatabaseHelper(getApplicationContext());
			final EditText s = (EditText) findViewById(R.id.editTextSearch);
			search = s.getText().toString();
			meds = db.searchMedications(currentUser, search);	
			
			Collections.sort(meds, new MedicationComparator());
			
			data = new ArrayList<Map<String, String>>();
			for (Medication med : meds) {
			    Map<String, String> datum = new HashMap<String, String>(2);
			    datum.put("name", med.getName());
			    datum.put("genName", med.getGenName());
			    data.add(datum);
			}
			
			
			adapter = new SimpleAdapter(this, data,R.layout.medication_row,
					new String[] {"name", "genName"},new int[] {R.id.toptext,R.id.bottomtext});
										
			ListView itemList = (ListView)findViewById(R.id.listViewSearch);
			itemList.setAdapter(adapter);
			itemList.setEmptyView(findViewById(R.id.empty));
			db.closeDB();
		}
	}
	
	/**
	 * Set up the {@link android.app.ActionBar}.
	 */
	private void setupActionBar() {

		getActionBar().setDisplayHomeAsUpEnabled(true);

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.search, menu);
		return true;
	}
	
	Intent intent;
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			// This ID represents the Home or Up button. In the case of this
			// activity, the Up button is shown. Use NavUtils to allow users
			// to navigate up one level in the application structure. For
			// more details, see the Navigation pattern on Android Design:
			//
			// http://developer.android.com/design/patterns/navigation.html#up-vs-back
			//
			NavUtils.navigateUpFromSameTask(this);
			return true;
		case R.id.action_logout:
			intent = new Intent(this, Login.class);
	    	startActivity(intent);
	    	finish();
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
		// TODO Auto-generated method stub
		return false;
	}
}
